package com.example.sss.controller;


import com.example.sss.controller.VO.SharedFileVO;
import com.example.sss.dao.FileMapper;
import com.example.sss.model.domin.Actor;
import com.example.sss.model.domin.HeatRecord;
import com.example.sss.model.domin.ObsFile;
import com.example.sss.model.domin.SharedFile;
import com.example.sss.model.utils.ObsPage;
import com.example.sss.service.ActorService.ActorService;
import com.example.sss.service.ArithmeticService.ArithmeticService;
import com.example.sss.service.FlileService.FileService;
import com.example.sss.service.LogService.LogOperate;
import com.example.sss.service.ObjectService.BucketObjectService;
import com.example.sss.service.SharedFileService.SharedFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author 王婷婷
 */
@Api(tags = "共享文件组管理接口")
@RequestMapping("/sharedFiles")
@RestController
public class SharedFileController {

    @Autowired
    private SharedFileService sharedFileService;
    @Autowired
    private BucketObjectService bucketObjectService;
    @Autowired
    private LogOperate logOperate;
    @Autowired
    private FileService fileService;
    @Autowired
    private ArithmeticService arithmeticService;
    @Autowired
    private FileMapper fileMapper;


    @PostMapping("/upload")
    @ResponseBody
    public int uploadOne(@RequestParam("file") MultipartFile fileUpload, Integer userId,Integer fileGroup, Integer sharedFileId, String path, Integer isShaerd) throws IOException {
        //获取文件名
        String fileName = fileUpload.getOriginalFilename();
        //获取文件后缀名  根据这个填类型
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        if (path==null){
            path="";
        }
        String absolutePath=path+fileName;
        //单位:b
        double size=fileUpload.getSize();

        //将MultipartFile转换成inputStream
        InputStream inputStream = null;
        File file = null;
        file = File.createTempFile("temp", null);
        fileUpload.transferTo(file);
        inputStream = new FileInputStream(file);
        file.deleteOnExit();
        //上传obs
        bucketObjectService.uploadFile(0,inputStream,absolutePath);

        //数据库添加文件
        ObsFile obsFile=new ObsFile();
        obsFile.setUserId(userId);
        obsFile.setType(fileService.getType(suffixName));
        if (size/1048576000>=1){
            obsFile.setSize(String.format("%.2f", size/1073741824) +" GB");
        }else if (size/1024000>=1){
            obsFile.setSize(String.format("%.2f", size/1048576) +" MB");
        }else if(size/1000>=1){
            obsFile.setSize(fileUpload.getSize()/1024 +" KB");
        }else {
            obsFile.setSize(fileUpload.getSize() +" B");
        }
        ObsFile dstFile=fileMapper.getSharedFileByPath(absolutePath);
        //存在同名文件需要删掉
        if(dstFile!=null){
            fileMapper.deleteFile(dstFile.getFileId());
        }
        //添加文件
        obsFile.setFileState(1);
        obsFile.setMakeTime(new Date());
        obsFile.setFileName(fileName);
        obsFile.setPath(absolutePath);
        obsFile.setIsShared(isShaerd);
        int i = fileService.addFile(obsFile);
        //添加热度初始值
        HeatRecord heatRecord = new HeatRecord();
        heatRecord.setFileId(i);
        if (fileGroup == 1){
            heatRecord.setHinit(10);
        }
        heatRecord.setUserId(userId);
        arithmeticService.addHinit(heatRecord);
        //添加共享组关联
        return sharedFileService.addSharedFiles(sharedFileId,obsFile.getFileId());
    }
    /**
     * 共享复制
     * @return
     */
    @PostMapping("/sharedCopy")
    public int sharedCopy(@RequestBody ObsFile obsFile ){
        fileService.copySharedFile(obsFile);
        try {
            bucketObjectService.copy(0,obsFile.getFileName(),obsFile.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }
    /**
     * 重命名文件
     * @return
     */
    @PostMapping("/rename")
    public int  rename(@RequestBody ObsFile obsFile) throws IOException {
        ObsFile dstFile=fileMapper.getSharedFileByPath(obsFile.getPath());
        //存在同名文件需要删掉
        if(dstFile!=null){
            return 2;
        }
        //改obs
        bucketObjectService.rename(0,obsFile.getFileName(),obsFile.getPath());
        //改数据库
        fileService.updateFileName(obsFile);
        return 1;
    }
    /**
     * 共享移动
     * @return
     */
    @PostMapping("/move")
    public String move(@RequestBody ObsFile obsFile ){
        //obs 移动  id、文件名  obsFile
        // 目的文件名 为了方便，我暂时放在 obsFile的path
        try {
            bucketObjectService.move(0,obsFile.getFileName(),obsFile.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //修改数据库
        fileService.updateSharedFilePath(obsFile);
        return "1";
    }
    /**
     * 查询列表
     * @param sharedFile
     * @return
     */
    @RequestMapping(value="/selectSharedFileList",method= RequestMethod.POST)
    public ObsPage selectSharedFileList(@RequestBody SharedFile sharedFile) {
        return sharedFileService.selectSharedFile(sharedFile);
    }
    /**
     * 预览操作记录日志
     * @param obsFile
     * @return
     */
    @RequestMapping(value="/addPreviewLog",method= RequestMethod.POST)
    public int addPreviewLog(@RequestBody ObsFile obsFile) {
        return logOperate.previewLog(obsFile);
    }
    /**
     * 下载操作记录日志
     * @param obsFile
     * @return
     */
    @RequestMapping(value="/addDownLoadLog",method= RequestMethod.POST)
    public int addDownLoadLog(@RequestBody ObsFile obsFile) {
        return logOperate.downLoadLog(obsFile);
    }
    /**
     * 查询共享文件组文件列表信息
     * @param sharedFile
     * @return
     */
    @ApiOperation(value = "查询共享文件组文件信息")
    @RequestMapping(value="/selectSharedFilesList",method= RequestMethod.POST)
    public ObsPage selectSharedFilesList(@RequestBody SharedFile sharedFile) {
        return sharedFileService.selectSharedFilesList(sharedFile);
    }
    /**
     * 查询推荐的文件信息
     * @param userId
     * @return
     */
    @RequestMapping(value="/selectRecommendFiles",method= RequestMethod.POST)
    public List<ObsFile> selectRecommendFiles(@RequestBody Integer userId) {
        List<Integer> idList = arithmeticService.arithmetic(userId);
        if (idList.size()>0){
            List<ObsFile> obsFiles = fileService.selectFileListByIds(idList);
            if (obsFiles.size()>3){
                return obsFiles.subList(0,3);
            } else {
                return obsFiles;
            }
        } else {
            return new ArrayList<>();
        }
    }
    /**
     * 查询热度前十
     * @param userId
     * @return
     */
    @RequestMapping(value="/selectTop10Files",method= RequestMethod.POST)
    public List<ObsFile> selectTop10Files(@RequestBody Integer userId) {
        List<ObsFile> obsFileList = new ArrayList<>();
        List<Integer> idList = arithmeticService.heatTop10(userId);
        if (idList.size()>0){
            for (Integer id : idList) {
                ObsFile obsFile = fileService.selectFileListById(id);
                obsFileList.add(obsFile);
            }
            return obsFileList;
        } else {
            return obsFileList;
        }
    }
    /**
     * 查询共享组用户详情
     * @param sharedFile
     * @return
     */
    @RequestMapping(value="/selectSharedFileUser",method= RequestMethod.POST)
    public SharedFileVO selectSharedFileUser(@RequestBody SharedFile sharedFile) {
        return sharedFileService.selectSharedFileUser(sharedFile);
    }
    /**
     * 添加
     * @param sharedFileVO
     * @return
     */
    @RequestMapping(value="/add",method= RequestMethod.POST)
    public int add(@RequestBody SharedFileVO sharedFileVO) throws IOException {
        return sharedFileService.addSharedFile(sharedFileVO.getSharedFile(),sharedFileVO.getUserList());
    }
    /**
     * 修改状态（逻辑删除）
     * @param sharedFile
     * @return
     */
    @RequestMapping(value="/update",method= RequestMethod.POST)
    public int update(@RequestBody SharedFile sharedFile) {
        return sharedFileService.updateSharedFile(sharedFile);
    }
    /**
     * 修改信息
     * @param
     * @return
     */
    @RequestMapping(value="/updateShared",method= RequestMethod.POST)
    public int updateShared(@RequestBody SharedFileVO sharedFileVO) {
        return sharedFileService.updateShared(sharedFileVO);
    }
    /**
     * 添加文件夹
     * @return
     */
    @PostMapping("/addFloder")
    public int addFloder(@RequestBody ObsFile obsFile ) throws IOException {
        //obs 移动  id、文件名
        bucketObjectService.newFolder(0,obsFile.getPath());
        //数据库操作
        obsFile.setType("文件夹");
        obsFile.setIsShared(1);
        fileService.addFile(obsFile);
        //共享组添加文件
        sharedFileService.addSharedFiles(obsFile.getSharedId(),obsFile.getFileId());
        return 1;
    }
    /**
     * 删除共享组文件
     * @return
     */
    @PostMapping("/deleteFile")
    public int deleteFile(@RequestBody ObsFile obsFile) throws IOException {
        if("文件夹".equals(obsFile.getType())){
            //删obs
            bucketObjectService.DropFolder(0,obsFile.getPath());
        }else{
            bucketObjectService.removeFile(0,obsFile.getPath());
        }
        //删除共享组关联
        sharedFileService.deleteSharedFile(obsFile.getSharedId(),obsFile.getFileId());
        //删除热度记录
        arithmeticService.deleteRecord(obsFile.getFileId());
        //删数据库
        fileService.deleteFile(obsFile);
        return 1;
    }

    /**
     * 增加互动值热度
     * @param heatRecord
     * @return
     */
    @PostMapping("/addHinteractRecord")
    public int addHinteractRecord(@RequestBody HeatRecord heatRecord) {
        if ("1".equals(heatRecord.getFlag())){
            heatRecord.setHinteract(5);
        } else {
            heatRecord.setHinteract(2);
        }
        return arithmeticService.addHinteractRecord(heatRecord);
    }
}
